package dao;

import java.util.ArrayList;
import java.util.Collections;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import util.ApplicationConstant;

import com.activity.MainAppActivity;
import com.fragment.ListLocateFragment;
import com.fragment.MainFragment;

import entities.Category;
import entities.Locate;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;

public class LoadLocate extends AsyncTask<String, Void, String> {
	private int distance;
	public static ArrayList<Locate> listLocate = new ArrayList<Locate>();
	public static Thread loadImageThread[];
	// neu load khi onsroll thi k hien progress dialog
	private Boolean calledFromScroll = false;

	public Boolean getCalledFromScroll() {
		return calledFromScroll;
	}

	public void setCalledFromScroll(Boolean calledFromScroll) {
		this.calledFromScroll = calledFromScroll;
	}

	public LoadLocate(int distance, String name) {
		this.distance = distance;
		if (calledFromScroll == false) {
			
		}
	}

	private static Handler handlerImage = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Log.d("loaded", "------------");
			ListLocateFragment.adapterLocate.notifyDataSetChanged();

		};
	};
	private static Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpPostThread.SUCCESS: {
				String answer = (String) msg.obj;
				try {
					JSONObject jsonObj = new JSONObject(answer);
					JSONArray jsonArray = jsonObj
							.getJSONArray(ApplicationConstant.JSON_ARRAY_LOCATES);
					Log.d("Size:", "" + jsonArray.length());
					// if(jsonArray.length()==0)
					// ListLocate.txtLoading.setText("");
					for (int i = 0; i < jsonArray.length(); i++) {
						Locate locate = new Locate();
						JSONObject jsonObject = jsonArray.getJSONObject(i);
						String id = jsonObject
								.getString(ApplicationConstant.COL_LOCATE_ID);
						Log.d("----load locate id:", id);
						String name = jsonObject.getString(
								ApplicationConstant.COL_LOCATE_NAME).trim();
						String address = jsonObject
								.getString(ApplicationConstant.COL_LOCATE_ADDRESS);
						String caId = jsonObject
								.getString(ApplicationConstant.COL_LOCATE_CATEGORY);

						String information = jsonObject
								.getString(ApplicationConstant.COL_LOCATE_INFORMATION);
						String latitude = jsonObject
								.getString(ApplicationConstant.COL_LOCATE_LATITUDE);
						String longtitude = jsonObject
								.getString(ApplicationConstant.COL_LOCATE_LONGTITUDE);
						String phone = jsonObject
								.getString(ApplicationConstant.COL_LOCATE_PHONE);
						String email = jsonObject
								.getString(ApplicationConstant.COL_LOCATE_EMAIL);
						String website = jsonObject
								.getString(ApplicationConstant.COL_LOCATE_WEBSITE);

						locate.setAdress(address);
						locate.setCategoryId(caId);
						locate.setWebsite(website);
						locate.setId(Integer.parseInt(id));
						locate.setInfor(information);
						locate.setLa(Double.parseDouble(latitude));
						locate.setLog(Double.parseDouble(longtitude));
						locate.setName(name);
						locate.setPhone(phone);
						locate.setEmail(email);
						JSONArray images = jsonObject
								.getJSONArray("listImageSrc");
						for (int j = 0; j < images.length(); j++) {
							String img = images.getJSONObject(j).getString(
									"imageSrc");
							locate.getImageNames().add(img);
						}
						// Log.d("image lenght:", ""+images.length());
						Log.d("Name:", name);
						listLocate.add(locate);
					}
					Collections.sort(listLocate);
					ListLocateFragment.adapterLocate.notifyDataSetChanged();
					// update textview result
					if (listLocate.size() > 0) {
						ListLocateFragment.txtTotalResults.setText(""
								+ listLocate.size() + " "
								+ ListLocateFragment.RESULTS);
						ListLocateFragment.notFoundLayout
								.setVisibility(View.GONE);
					} else {
						ListLocateFragment.txtTotalResults.setText(""
								+ listLocate.size() + " "
								+ ListLocateFragment.RESULT);
						ListLocateFragment.notFoundLayout
								.setVisibility(View.VISIBLE);
					}

				} catch (JSONException e) {
				}

				// load bit map in new thread
				Bitmap defaultBitMap = null;
				if (listLocate.size() > 0)
					for (Category c : MainFragment.listCategory) {
						if (c.getCategoryId()
								.trim()
								.equals(listLocate.get(0).getCategoryId()
										.trim())) {
							defaultBitMap = c.getBitmap();
							break;
						}
					}
				final Bitmap bitmapDefaulf = defaultBitMap;
				loadImageThread = new Thread[listLocate.size()];
				int i = 0;
				for (final Locate locate : listLocate) {
					locate.loadItemImage(handlerImage);
					i++;
				}
			}
				break;
			case HttpPostThread.FAILURE:
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onPostExecute(String result) {
		ListLocateFragment.linearLayoutLoading.setVisibility(View.GONE);
		if (calledFromScroll == true)
			ListLocateFragment.isLoadingList = false;

		// ListLocate.txtLoading.setText("");
		ListLocateFragment.progressBar.setVisibility(View.GONE);

	};

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		if (calledFromScroll == false)
			ListLocateFragment.linearLayoutLoading.setVisibility(View.VISIBLE);
		else
			// ListLocate.txtLoading.setText("Loading more...");
			ListLocateFragment.progressBar.setVisibility(View.VISIBLE);

	}

	@Override
	protected String doInBackground(String... arg0) {
		// TODO Auto-generated method stub
		try {
			Log.d("-----getting lcoate", "");
			Log.d(ApplicationConstant.ACTION_CATEGORY_ID,
					ListLocateFragment.caId);
			Log.d(ApplicationConstant.ACTION_LATITUDE, ""
					+ MainAppActivity.orginalLatl.latitude);
			Log.d(ApplicationConstant.ACTION_LONGTITUDE, ""
					+ MainAppActivity.orginalLatl.longitude);
			Log.d(ApplicationConstant.ACTION_DISTANCE, ""
					+ String.valueOf(distance));
			Log.d(ApplicationConstant.ACTION_FROM, ""
					+ String.valueOf(listLocate.size()));
			
			
			ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
			pairs.add(new BasicNameValuePair(
					ApplicationConstant.ACTION,
					ApplicationConstant.ACTION_GET_LOCATE_BY_CATERORY_AND_DISTANCE));
			pairs.add(new BasicNameValuePair(
					ApplicationConstant.ACTION_LATITUDE, String
							.valueOf(MainAppActivity.orginalLatl.latitude)));
			pairs.add(new BasicNameValuePair(
					ApplicationConstant.ACTION_LONGTITUDE, String
							.valueOf(MainAppActivity.orginalLatl.longitude)));
			pairs.add(new BasicNameValuePair(ApplicationConstant.ACTION_FROM,
					String.valueOf(listLocate.size())));
			pairs.add(new BasicNameValuePair(
					ApplicationConstant.ACTION_CATEGORY_ID, String
							.valueOf(ListLocateFragment.caId)));
			pairs.add(new BasicNameValuePair(
					ApplicationConstant.ACTION_DISTANCE, String
							.valueOf(distance)));
			HttpPostThread thread = new HttpPostThread(
					ApplicationConstant.URL_LOCATE, pairs, handler);
			thread.run();
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
		return null;
	}
}
